package imaLogin

import (
	"crypto/tls"
	"encoding/json"
	"fmt"
	"io"
	"local/config"
	"net/http"

	"github.com/gin-gonic/gin"
)

type UserResponse struct {
	Code    int  `json:"code"`
	Success bool `json:"success"`
	Data    struct {
		UserInfo struct {
			ID        string `json:"id"`
			CompanyID string `json:"companyId"`
			OrgID     int    `json:"orgId"`
			LoginName string `json:"loginName"`
			No        string `json:"no"`
			Password  string `json:"password"`
		} `json:"userInfo"`
	} `json:"data"`
	Msg string `json:"msg"`
}

func LoginClient(c *gin.Context) {
	iamCode := c.Query("iamCode")
	if iamCode == "" {
		c.HTML(http.StatusBadRequest, "error.html", gin.H{
			"ErrorMessage": "缺少必要的参数",
		})
		return
	}

	// 忽略证书
	tr := &http.Transport{
		TLSClientConfig: &tls.Config{InsecureSkipVerify: true},
	}
	client := &http.Client{
		Transport: tr,
	}

	// 发起验证请求
	resp, err := client.Get(
		fmt.Sprintf(
			"%s/ims-idms/usersession/getUserInfoByCode?iamCode=%s&clientId=",
			config.Inst.ImaApi.Server,
			iamCode))
	if err != nil {
		c.HTML(http.StatusInternalServerError, "error.html", gin.H{
			"ErrorMessage": "服务器请求失败：" + err.Error(),
		})
		return
	}
	// fmt.Println("响应状态码：", resp.StatusCode)
	defer resp.Body.Close()

	body, err := io.ReadAll(resp.Body)
	if err != nil {
		c.HTML(http.StatusInternalServerError, "error.html", gin.H{
			"ErrorMessage": "读取响应失败：" + err.Error(),
		})
		return
	}

	var userResp UserResponse
	if err := json.Unmarshal(body, &userResp); err != nil {
		c.HTML(http.StatusInternalServerError, "error.html", gin.H{
			"ErrorMessage": "解析响应失败：" + err.Error(),
		})
		return
	}

	if userResp.Code != 200 {
		c.HTML(http.StatusBadRequest, "error.html", gin.H{
			"ErrorMessage": userResp.Msg,
		})
		return
	}

	// 调用有度登录
	updateConfig()

	username := userResp.Data.UserInfo.No
	if username == "" {
		username = userResp.Data.UserInfo.LoginName
	}

	tokenLink, err := sso.GetLoginLink(username)
	if err != nil {
		c.HTML(http.StatusInternalServerError, "error.html", gin.H{
			"ErrorMessage": "获取有度启动链接失败：" + username + " | " + err.Error(),
		})
		return
	}
	// 渲染client.html模板
	c.HTML(http.StatusOK, "client.html", gin.H{
		"TokenLink": tokenLink,
		"ClientUrl": config.Inst.Entprise.ClientUrl,
		"Countdown": config.Inst.ServiceYouSSO.Countdown,
	})
}
